<template>
  <div class="my-revoke">
    <van-nav-bar
      :title="generateTitle($route.name,$route.params.title||$route.meta.title)"
      :left-text="$t('back')"
      :right-text="rightText"
      left-arrow
      fixed
      @click-left="$router.push({ name: 'dashboard' })"
      @click-right="toCheckMode()"/>

    <van-search
      v-model="subject"
      @search="onSearch"
    />
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" @load="onLoad">
        <div v-for="(item,index) in list" :key="item.id+index">
          <van-swipe-cell :right-width="65">
            <van-cell-group >
              <card-list
                :title="item.procDefName"
                :desc="item.subject"
                :date="item.createTime|formatTime"
                :tag="_getStatus(item.status)"
                :tag-type="_getStatusType(item.status)"
                :bg-color="_randomColor(index)"
                :icon="_randomIcon(index)"
                :check-mode="checkMode"
                :checked="checkedIds.includes(item.taskId)"
                is-link
                @click="onClick(item)"/>
            </van-cell-group>
            <span slot="right" @click="onRevoke(item.taskId)">{{ $t('common.button.revoke') }}</span>
          </van-swipe-cell>
        </div>
        <list-result-page
          :result-type="resultType"
          :error-type="errorType"
          :result-message="resultMessage"/>
      </van-list>
    </van-pull-refresh>
    <van-popup slot="fr-ext" v-model="popup" class="lc-fullscreen-popup">
      <div class="lc-fixed-top">
        <van-nav-bar
          :title="$t('common.button.revoke')"
          :left-text="$t('close')"
          left-arrow
          fixed
          @click-left="popup=false"
        />
        <van-cell-group>
          <van-field
            v-validate="{ required: true}"
            v-model="form.opinion"
            :error="errors.has('opinion')"
            :error-message="errors.first('opinion')"
            label="原因"
            type="textarea"
            placeholder="请输入意见"
            rows="4"
            autosize
            required
            name="opinion"
          />
        </van-cell-group>
        <lc-toolbar
          :actions="actions"/>
      </div>
    </van-popup>
    <lc-toolbar
      v-show="checkMode"
      :actions="mainActions"/>
  </div>
</template>
<script>
import CardList from '@/components/CardList'
import ListResultPage from '@/components/ListResultPage'
import LcToolbar from '@/components/LcToolbar'

import { myRevoke } from '@/api/platform/bpmn/bpmn'
import { complete } from '@/api/platform/bpmn/action'

import { formatParams, loadFinished, getResultType } from '@/utils/params'
import random from '@/mixins/random'
import bpmnStatus from '@/mixins/bpmnStatus'
import i18n from '@/utils/i18n'

export default {
  components: {
    CardList,
    ListResultPage,
    LcToolbar
  },
  mixins: [random, bpmnStatus],
  data() {
    return {
      subject: '',
      list: [],
      page: 1,
      loading: false,
      finished: false,
      isLoading: true,
      resultType: 'init',
      errorType: null,
      resultMessage: null,
      popup: false,
      form: {
        taskId: '',
        opinion: '',
        actionName: 'revoke'
      },
      checkMode: false,
      checkedIds: [],
      actions: [{
        'name': this.$t('common.button.save'),
        'buttonType': 'primary',
        'callback': this.onValidate
      }],
      mainActions: [{
        'name': this.$t('common.button.revoke'),
        'buttonType': 'danger',
        'callback': this.onRevoke
      }]
    }
  },
  computed: {
    rightText() {
      if (this.list.length > 0) {
        return this.checkMode ? this.$t('common.button.cancel') : this.$t('common.button.manage')
      }
      return null
    }
  },
  methods: {
    generateTitle(name, title) { // generateTitle by vue-i18n
      return i18n.generateTitle(name, title)
    },
    getData() {
      const params = formatParams({ 'Q^subject_^SL': this.subject }, { 'page': this.page })
      myRevoke(params).then(response => {
        if (this.$utils.isNotEmpty(response.data.dataResult)) {
          this.page++
          this.list = this.list.concat(response.data.dataResult)
          this.finished = false
        }
        this.finished = !!loadFinished(response.data.pageResult)
        this.loading = false
        this.isLoading = false
        // 结果类型
        this.resultType = getResultType(this.list, this.finished)
      }).catch((e) => {
        this.loading = false
        this.isLoading = false
        this.finished = true
        this.resultType = 'error'
        this.resultMessage = e.message
      })
    },
    onSearch() {
      this.resultType = 'init'
      this.page = 1
      this.list = []
      this.getData()
    },
    onLoad() {
      this.getData()
    },
    onRefresh() {
      this.resultType = 'init'
      this.isLoading = true
      this.page = 1
      this.list = []
      this.getData()
    },
    onRefreshPage() {
      this.checkMode = false
      this.onRefresh()
    },
    onClick(item) {
      if (this.checkMode) {
        const index = this.checkedIds.indexOf(item.taskId)
        if (index > -1) {
          this.checkedIds.splice(index, 1)
        } else {
          this.checkedIds.push(item.taskId)
        }
      } else {
        this.$router.push({
          name: 'bpmnForm',
          query: {
            instanceId: item.id
          },
          params: {
            title: item.procDefName
          }})
      }
    },
    onRevoke(item) {
      if (item.name) {
        if (this.checkedIds.length === 0) {
          return this.$toast(this.$t('common.dialog.selectedRecords'))
        }
        if (this.checkedIds.length > 1) {
          return this.$toast(this.$t('common.dialog.multipleSelected'))
        }
        this.form.taskId = this.checkedIds[0]
      } else {
        this.form.taskId = item
      }
      this.popup = true
    },
    onSave() {
      complete(this.form).then(response => {
        this.$toast.success(`撤销成功！`)
        this.popup = false
        this.onRefreshPage()
      }).catch(e => {
        console.error(e)
      })
    },
    onValidate() {
      this.$validator.validateAll().then((result) => {
        if (result) {
          this.onSave()
        } else {
          var name = document.getElementsByName(this.errors.items[0].field)
          if (name) {
            name[0].focus()
          }
          this.$toast('表单未正确填写！')
        }
      })
    },
    toCheckMode() {
      if (this.checkMode) {
        this.show = true
      }
      this.checkMode = !this.checkMode
    }
  }

}
</script>

<style lang="scss" >
  .my-revoke{
    .van-swipe-cell__right {
      color: #FFFFFF;
      font-size: 15px;
      width: 65px;
      height: 52px;
      display: inline-block;
      text-align: center;
      line-height: 50px;
      background-color: #F44;
    }
  }
</style>
